package com.ilovepostcard.view;

import java.util.ArrayList;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.ilovepostcard.EmptyActivity;
import com.ilovepostcard.MyActivity;
import com.ilovepostcard.PostcardActivity;
import com.ilovepostcard.PrintChangeTypeActivity;
import com.ilovepostcard.R;
import com.ilovepostcard.UserActivity;
import com.ilovepostcard.controller.BaseAsyncTask;
import com.ilovepostcard.controller.OffLineManager;
import com.ilovepostcard.controller.ServerAsyncTask;
import com.ilovepostcard.controller.UserController;
import com.ilovepostcard.controller.server.IServer;
import com.ilovepostcard.controller.server.PostcardResult;
import com.ilovepostcard.controller.server.ServerFactory;
import com.ilovepostcard.model.Order;
import com.ilovepostcard.model.Postcard;
import com.ilovepostcard.model.SimpleUser;
import com.ilovepostcard.model.User;
import com.ilovepostcard.utils.Constants;
import com.ilovepostcard.utils.Utils;
import com.ilovepostcard.view.PostcardGridView.OnPostcardClickListener;
import com.ilovepostcard.view.PostcardGridView.OnPostcardLongClickListener;
import com.ilovepostcard.view.UserGridView.OnUserClickListener;
import com.ilovepostcard.view.UserGridView.OnUserLongClickListener;
import com.mobclick.android.MobclickAgent;

public class PostcardMyView2 extends PostcardDiscoverView2 {

    PostcardGridView chuangzuojiGridView;
    PostcardGridView offlineBoxGridView;
    View offlineButtons;
    UserGridView followingGridView;
    UserGridView followedByGridView;
    ListView orderListView;
    View gotochartButton;
    TextView orderEmpty;
    OrderAdapter orderAdapter;
    
    ArrayList<Order> mOrderList;
    
    public PostcardMyView2(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    public PostcardMyView2(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public PostcardMyView2(Context context) {
        super(context);
    }

    @Override
    protected int getLayoutID() {
        return R.layout.my_main2;
    }

    @Override
    protected int[] getTabIDs() {
        return new int[] { R.id.my_tab_postcards, R.id.my_tab_following, R.id.my_tab_followed_by,
                R.id.my_tab_offline_box, R.id.my_tab_order };
    }

    @Override
    protected int[] getContentIDs() {
        return new int[] { R.layout.tab_content_changzuoji, R.layout.tab_content_following,
                R.layout.tab_content_followed, R.layout.tab_content_offline_box, R.layout.tab_content_order };
    }
    
    @Override
    protected void onPageChange(int page) {
        if (page == 0) {
            if (!chuangzuojiGridView.isLoaded())
                chuangzuojiGridView.loadNextPage();
        } else if (page == 1) {
            if (!followingGridView.isLoaded())
                followingGridView.loadNextPage();
        } else if (page == 2) {
            if (!followedByGridView.isLoaded())
                followedByGridView.loadNextPage();
        } else if (page == 3) {
        	MobclickAgent.onEvent(PostcardMyView2.this.getContext(), Constants.COUNT_MY_OFFLINE);
            if (!offlineBoxGridView.isLoaded()) {
                offlineBoxGridView.loadNextPage(new Runnable() {
                    
                    @Override
                    public void run() {
                        offlineButtons.setVisibility(offlineBoxGridView.getSize() > 0 ? VISIBLE : GONE);
                    }
                });
            }
        } else if (page == 4) {
        	MobclickAgent.onEvent(PostcardMyView2.this.getContext(), Constants.COUNT_MY_ORDER);
            if (mOrderList == null) {
                new ServerAsyncTask(getContext()) {
                    
                    @Override
                    protected void onSuccess(PostcardResult result) {
                    	orderEmpty.setText(R.string.empty_order);
                        mOrderList = new ArrayList<Order>();
                        ArrayList<Order> list = result.getOrderList();
                        if (list != null)
                            mOrderList.addAll(list);
                        orderAdapter.notifyDataSetChanged();
                        gotochartButton.setVisibility(mOrderList.size() == 0 ? GONE : VISIBLE);
                    }
                    
                    @Override
                    protected PostcardResult doRequest() {
                        User loginUser = UserController.getLoginUser(getContext());
                        return ServerFactory.getServer().listOrder(loginUser.UserID, 1, 1000);
                    }
                }.execute();
            }
        }
    }
    
    @Override
    protected void setupView() {
        chuangzuojiGridView = (PostcardGridView)getContentView(0).findViewById(R.id.my_chuangzuoji);
        offlineBoxGridView = (PostcardGridView)getContentView(3).findViewById(R.id.my_offline_box_gridview);
        offlineButtons = getContentView(3).findViewById(R.id.offline_buttons);
        followingGridView = (UserGridView)getContentView(1).findViewById(R.id.my_following);
        followedByGridView = (UserGridView)getContentView(2).findViewById(R.id.my_followed_by);
        orderListView = (ListView)getContentView(4).findViewById(R.id.my_ordery);
        gotochartButton = getContentView(4).findViewById(R.id.gotochart);
        orderEmpty = (TextView)getContentView(4).findViewById(android.R.id.empty);
        orderEmpty.setText("");
        orderListView.setEmptyView(orderEmpty);
        
        gotochartButton.setOnClickListener(new View.OnClickListener() {
            
            @Override
            public void onClick(View v) {
                new ServerAsyncTask(getContext()) {
                    
                    @Override
                    protected void onSuccess(PostcardResult result) {
                        /*Intent intent = new Intent(Intent.ACTION_VIEW);
                        Uri uri = Uri.parse(result.getBuyChartUrl());
                        intent.setData(uri);
                        getContext().startActivity(intent);
                        */
                    	
                        Intent nextPage = new Intent(getContext(),EmptyActivity.class);
	    				Bundle extras = new Bundle();
	    				extras.putString("url", result.getBuyChartUrl());
	    				extras.putBoolean("type", true);
	    				nextPage.putExtras(extras);
	    				getContext().startActivity(nextPage);
                    }
                    
                    @Override
                    protected PostcardResult doRequest() {
                        return ServerFactory.getServer().GetBuycartUrl(UserController.getLoginUser(getContext()).UserID);
                    }
                }.execute();
            }
        });
        
        chuangzuojiGridView.setOnPostcardClickListener(new OnPostcardClickListener() {

            @Override
            public void onClick(final Postcard postcard) {
                Intent intent = new Intent(getContext(), PostcardActivity.class);
                intent.putExtra("postcard", postcard);
                intent.putExtra("view", "my");
                getContext().startActivity(intent);
            }

        });
        chuangzuojiGridView.setOnPostcardLongClickListener(new OnPostcardLongClickListener() {

            @Override
            public void onLongClick(final Postcard postcard) {
                
                Utils.showChooseDialog(getContext(), new String[] { "分享明信片", "印制实体明信片", "删除明信片" }, new Runnable[] {
                    new Runnable() {
                        public void run() {
                        	MobclickAgent.onEvent(PostcardMyView2.this.getContext(), Constants.COUNT_MY_CARD_SHARE);
                        	com.ilovepostcard.utils.ThirdPartyLoginUtil.shareToOther(getContext(), postcard.PostcardID);
                        }
                    },
                    new Runnable() {
                        public void run() {
                        	
                        	MobclickAgent.onEvent(PostcardMyView2.this.getContext(), Constants.COUNT_MY_CARD_PRINT);
                        	Intent nextPage = new Intent(getContext(),PrintChangeTypeActivity.class);
                        	Bundle bundle = new Bundle();
                        	bundle.putSerializable("postcard", postcard);
                        	nextPage.putExtras(bundle);
                        	getContext().startActivity(nextPage);
                        }
                    },
                    new Runnable() {
                        public void run() {
                        	MobclickAgent.onEvent(PostcardMyView2.this.getContext(), Constants.COUNT_MY_CARD_DELETE);
                            new ServerAsyncTask(getContext()) {

                                @Override
                                protected PostcardResult doRequest() {
                                    User loginUser = UserController.getLoginUser(getContext());
                                    return ServerFactory.getServer().deletePostcard(postcard.PostcardID, loginUser.UserID);
                                }

                                @Override
                                protected void onSuccess(PostcardResult result) {
                                    chuangzuojiGridView.removePostcard(postcard);
                                    ((MyActivity)getContext()).onDeletePubSuccess();
                                    Toast.makeText(getContext(), R.string.success_delete, Toast.LENGTH_SHORT).show();
                                }
                                
                            }.execute();
                        }
                    }
                });
                
            }
        });
        
        offlineBoxGridView.setOnPostcardClickListener(new OnPostcardClickListener() {

            @Override
            public void onClick(final Postcard postcard) {
                Intent intent = new Intent(getContext(), PostcardActivity.class);
                intent.putExtra("postcard", postcard);
                getContext().startActivity(intent);
            }

        });
        
        offlineBoxGridView.setOnPostcardLongClickListener(new OnPostcardLongClickListener() {
            
            @Override
            public void onLongClick(final Postcard postcard) {
                Utils.showChooseDialog(getContext(), new String[] {"删除明信片"}, new Runnable[] {
                    new Runnable() {
                        public void run() {
                            boolean res = OffLineManager.getInstance().delete(postcard.offlineName);
                            if(res)
                            	offlineBoxGridView.removePostcard(postcard);
                            else
                            	Toast.makeText(getContext(),"现在不能删除这个明信片，请重启应用后重试.",Toast.LENGTH_SHORT).show();
                        }
                    }
                });
            }
        });
        
        View allUpload = getContentView(3).findViewById(R.id.all_upload);
        View selectUpload = getContentView(3).findViewById(R.id.select_upload);
        
        allUpload.setOnClickListener(new View.OnClickListener() {
            
            @Override
            public void onClick(View v) {
                offlineBoxGridView.selectAll();
                offlineBoxUploadSelected();
            }
        });
        selectUpload.setOnClickListener(new View.OnClickListener() {
            
            @Override
            public void onClick(View v) {
                offlineBoxUploadSelected();
            }
        });
        

        followingGridView.setOnUserClickListener(new OnUserClickListener() {

            @Override
            public void onClick(final SimpleUser user) {
                new ServerAsyncTask(getContext()) {
                    
                    @Override
                    protected void onSuccess(PostcardResult result) {
                        User detailUser = result.getUser();
                        Intent intent = new Intent(getContext(), UserActivity.class);
                        intent.putExtra("user", detailUser);
                        intent.putExtra("attention", true);
                        getContext().startActivity(intent);
                    }
                    
                    @Override
                    protected PostcardResult doRequest() {
                        return ServerFactory.getServer().getUserInfo("", user.UserID);
                    }
                }.execute();
                
            }
        });
        followingGridView.setOnUserLongClickListener(new OnUserLongClickListener() {

            @Override
            public void onLongClick(final SimpleUser user) {
                Utils.showChooseDialog(getContext(), new String[] {"取消关注"}, new Runnable[] {
                    new Runnable() {
                        public void run() {
                            new ServerAsyncTask(getContext()) {
                                
                                @Override
                                protected void onSuccess(PostcardResult result) {
                                    followingGridView.removeUser(user);
                                    Toast.makeText(getContext(), R.string.success_cancel_attention, Toast.LENGTH_SHORT).show();
                                }
                                
                                @Override
                                protected PostcardResult doRequest() {
                                    return ServerFactory.getServer().attention(UserController.getLoginUser(getContext()).UserID, user.UserID, IServer.ATTENTION_TYPE_CANCEL_FOLLOW);
                                }
                            }.execute();
                        }
                    }
                });
            }
        });

        followedByGridView.setOnUserClickListener(new OnUserClickListener() {

            @Override
            public void onClick(final SimpleUser user) {
                new ServerAsyncTask(getContext()) {
                    
                    @Override
                    protected void onSuccess(PostcardResult result) {
                        final User detailUser = result.getUser();
                        
                        new ServerAsyncTask(getContext()) {
                            
                            @Override
                            protected void onSuccess(PostcardResult result) {
                                Intent intent = new Intent(getContext(), UserActivity.class);
                                intent.putExtra("user", detailUser);
                                intent.putExtra("attention", result.getCheckAttention());
                                getContext().startActivity(intent);
                            }
                            
                            @Override
                            protected PostcardResult doRequest() {
                                return ServerFactory.getServer().checkAttention(UserController.getLoginUser(getContext()).UserID, detailUser.UserID);
                            }
                            
                        }.execute();
                    }
                    
                    @Override
                    protected PostcardResult doRequest() {
                        return ServerFactory.getServer().getUserInfo("", user.UserID);
                    }
                }.execute();
            }
        });
        
        followedByGridView.setOnUserLongClickListener(new OnUserLongClickListener() {

            @Override
            public void onLongClick(final SimpleUser user) {
                
                Utils.showChooseDialog(getContext(), new String[] {"关注"}, new Runnable[] {
                    new Runnable() {
                        public void run() {
                            new ServerAsyncTask(getContext()) {
                                
                                @Override
                                protected void onSuccess(PostcardResult result) {
                                    followingGridView.removeUser(user);
                                    Toast.makeText(getContext(), R.string.success_attention, Toast.LENGTH_SHORT).show();
                                }
                                
                                @Override
                                protected PostcardResult doRequest() {
                                    return ServerFactory.getServer().attention(UserController.getLoginUser(getContext()).UserID, user.UserID, IServer.ATTENTION_TYPE_FOLLOW);
                                }
                            }.execute();
                        }
                    }
                });
            }
        });
        
        orderAdapter = new OrderAdapter();
        orderListView.setAdapter(orderAdapter);
        orderListView.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id) {
                Order order = mOrderList.get(position);
                /*Intent intent = new Intent(Intent.ACTION_VIEW);
                Uri content_url = Uri.parse(order.OrderDetailUrl);
                intent.setData(content_url);  
                getContext().startActivity(intent);*/
                
                Intent nextPage = new Intent(getContext(),EmptyActivity.class);
				Bundle extras = new Bundle();
				extras.putString("url", order.OrderDetailUrl);
				extras.putBoolean("type", false);
				nextPage.putExtras(extras);
				getContext().startActivity(nextPage);
//                final long oid = order.OrderID;
//                new ServerAsyncTask(getContext()) {
//                    
//                    @Override
//                    protected void onSuccess(PostcardResult result) {
//                        Intent intent = new Intent(getContext(), OrderDetailActivity.class);
//                        intent.putExtra("order", result.getOrderInfo());
//                        getContext().startActivity(intent);
//                    }
//                    
//                    @Override
//                    protected PostcardResult doRequest() {
//                        return ServerFactory.getServer().getOrderInfo(oid);
//                    }
//                }.execute();
//                
                
            }
            
        });
//        orderListView
        
        onPageChange(0);
    }
    
    private void offlineBoxUploadSelected() {
        final String[] names = offlineBoxGridView.getSelectedOfflinePostcardName();
        if (names == null || names.length == 0)
            return;
        new BaseAsyncTask() {

            ProgressDialog pd;
            boolean success = true;
            
            
            @Override
            protected void _doInBackground() {
                int length = names.length;
                for (int i = 0; i < length; i++) {
                    PostcardResult result = OffLineManager.getInstance().uploadOffLinePc(getContext(),names[i]);
                    if (!result.isSuccess()) {
                        success = false;
                    }
                }
            }

            @Override
            protected void _onPostExecute() {
                offlineBoxGridView.reload();
                if (!success) {
                    Toast.makeText(getContext(), "上传失败", Toast.LENGTH_SHORT).show();
                }
                else
                {
                	Toast.makeText(getContext(), "已上传成功喽～", Toast.LENGTH_SHORT).show();
                }
                try {
                    pd.dismiss();
                } catch (Throwable t) {
                    
                }
                offlineButtons.setVisibility(offlineBoxGridView.getSize() > 0 ? VISIBLE : GONE);
            }

            @Override
            protected void _onPreExecute() {
                pd = new ProgressDialog(getContext());
                pd.setMessage(getLoadingMessage());
                pd.show();
            }
            
            protected String getLoadingMessage() {
                return getContext().getString(R.string.loading_data);
            }
            
        }.execute();
    }
    
    private class OrderAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            if (mOrderList != null)
                return mOrderList.size();
            return 0;
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            OrderRow or = new OrderRow(getContext());
            Order order = mOrderList.get(position);
            or.setOrder(order);
            return or;
        }
        
    }
}
